package org.luxor.commons.core.utils.encrypt;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

/**
 * PBE对称加解密工具类(兼容Jasypt) <对称加密算法>
 * <p>
 * 常用于程序配置参数的加密处理，避免明文暴露在配置文件中。如：ENC(mC8T2JogodBDrZgNJRU+Iw==)。
 * <p>
 *
 * @author Mr.yan @date 2019/10/20
 */
public class PbeEncryptUtils {

    /**
     * 默认密钥,不允许随意更改
     */
    public static final String DEFAULT_PUBLIC_KEY_STRING = "luxor@2019";

    /**
     * 默认算法
     */
    private static final String ALGORITHM = "PBEWithMD5AndDES";


    /**
     * PBE加密
     *
     * @param plaintext 明文
     * @return ciphertext 密文
     */
    public static String encrypt(String plaintext) {
        return encrypt(DEFAULT_PUBLIC_KEY_STRING, plaintext);
    }

    /**
     * PBE解密
     *
     * @param ciphertext 密文
     * @return plaintext 明文
     */
    public static String decrypt(String ciphertext) {
        return decrypt(DEFAULT_PUBLIC_KEY_STRING, ciphertext);
    }

    public static String encrypt(String publicPassword, String plaintext) {
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setAlgorithm(ALGORITHM);
        encryptor.setPassword(publicPassword);
        return encryptor.encrypt(plaintext);
    }

    public static String decrypt(String publicPassword, String ciphertext) {
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setAlgorithm(ALGORITHM);
        encryptor.setPassword(publicPassword);
        return encryptor.decrypt(ciphertext);
    }


    public static void main(String[] args) {
        // 解密
        String ciphertext = "0LvWrYl9RLhXGhnmGiX37w==";
        System.out.println("解密结果:" + decrypt(DEFAULT_PUBLIC_KEY_STRING, ciphertext));

        // 加密
        String plaintext = "123456";
        System.out.println("加密结果:" + String.format("ENC(%s)", encrypt(DEFAULT_PUBLIC_KEY_STRING, plaintext)));
    }

}